package cn.mai.service.impl;

import java.util.List;
import java.util.Random;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.mai.dao.ChatRepository;
import cn.mai.domain.Dialog;
import cn.mai.service.ChatService;

@Service
@Transactional
public class ChatServiceImpl implements ChatService {

	@Autowired
	private ChatRepository chatRepository;

	@Override
	public String findAnswer(Dialog dialog) {
		List<Dialog> dialogs = chatRepository.findByAsk(dialog.getAsk().trim());
		if (dialogs.size() == 0) {
			return null;
		}
		return dialogs.get(RandomUtils.nextInt(dialogs.size())).getAnswer();
	}

	@Override
	public void save(Dialog dialog) {
		dialog.setAsk(dialog.getAsk().trim());
		dialog.setAnswer(dialog.getAnswer().trim());
		chatRepository.save(dialog);
	}

}
